// pages/play/play.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getSetting({
      success: function (res) {
         app.globalData.loginTo = true
        if (res.authSetting['scope.userInfo']) {

          util.showLoading("登录中...")
          that.authorization();
        } else {
          that.setData({
            setLogin: "noLogin"
          })
        }
      }
    })


  },

  // 登录
  authorization: function () {
    var that = this
    wx.login({
      success: function (res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            var login_code = res_login.code;
            var login_encryptedData = res_user.encryptedData;
            var login_iv = res_user.iv;
            that.autoLogin(login_code, login_encryptedData, login_iv);
            that.setData({
              setLogin: 'login',
              avatarUrl: res_user.userInfo.avatarUrl,
              nickName: res_user.userInfo.nickName,
            });
          },
          fail: function (fail_res) {
            // if (fail_res.errMsg == "getUserInfo:fail auth deny") {
            // } else {
            //   util.showError("网络错误");
            // }
          }
        })
      },
      fail: function (fail_login) {
        util.showError("网络错误，请检查网络");
      }
    })
  },

  autoLogin: function (login_code, login_encryptedData, login_iv) {
    var that = this
    var params = {
      code: login_code,
      encryptedData: login_encryptedData,
      iv: login_iv
    }
    api.POST({
      params: params,
      url: app.globalData.login_url,
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.accountInfo = res.data.data.result;
          app.globalData.loginTo = true
          wx.setStorageSync('accountInfo', res.data.data.result)
          wx.navigateBack({
            delta: 1
          })
        }else{
           app.globalData.loginTo = true
        }
        util.hiddenLoading();
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
        util.hiddenLoading();
      }
    })
  },
  noAuth:function(){
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }

})